package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.service.HaohanLoanDataCleanupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 浩瀚小贷数据清理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/haohan-cleanup")
public class HaohanLoanCleanupController {
    
    @Autowired
    private HaohanLoanDataCleanupService haohanLoanDataCleanupService;
    
    /**
     * 获取当前浩瀚小贷未结清订单的总剩余金额
     */
    @GetMapping("/total-amount")
    public Map<String, Object> getTotalRemainAmount() {
        Map<String, Object> result = new HashMap<>();
        try {
            BigDecimal totalAmount = haohanLoanDataCleanupService.getTotalRemainAmount();
            result.put("success", true);
            result.put("totalAmount", totalAmount);
            result.put("message", "获取总剩余金额成功");
            log.info("当前浩瀚小贷未结清订单总剩余金额: {}", totalAmount);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取总剩余金额失败: " + e.getMessage());
            log.error("获取总剩余金额失败", e);
        }
        return result;
    }
    
    /**
     * 获取浩瀚小贷未结清订单按月份分组统计
     */
    @GetMapping("/monthly-stats")
    public Map<String, Object> getMonthlyOrderStats() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<HaohanLoanDataCleanupService.MonthlyOrderStats> stats = 
                    haohanLoanDataCleanupService.getMonthlyOrderStats();
            result.put("success", true);
            result.put("stats", stats);
            result.put("message", "获取月度统计成功");
            log.info("获取到 {} 个月份的统计数据", stats.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取月度统计失败: " + e.getMessage());
            log.error("获取月度统计失败", e);
        }
        return result;
    }
    
    /**
     * 执行数据清理，按月份平均删除数据
     * @param targetAmount 目标剩余金额（可选，默认六亿）
     */
    @PostMapping("/execute-cleanup")
    public Map<String, Object> executeCleanup(@RequestParam(value = "targetAmount", required = false) String targetAmount) {
        Map<String, Object> result = new HashMap<>();
        try {
            BigDecimal target = new BigDecimal("600000000"); // 默认六亿
            if (targetAmount != null && !targetAmount.trim().isEmpty()) {
                target = new BigDecimal(targetAmount);
            }
            
            log.info("开始执行数据清理，目标剩余金额: {}", target);
            HaohanLoanDataCleanupService.CleanupResult cleanupResult = 
                    haohanLoanDataCleanupService.executeCleanup(target);
            
            result.put("success", cleanupResult.isSuccess());
            result.put("message", cleanupResult.getMessage());
            result.put("originalAmount", cleanupResult.getOriginalAmount());
            result.put("finalAmount", cleanupResult.getFinalAmount());
            result.put("deletedOrders", cleanupResult.getTotalDeletedOrders());
            result.put("deletedCustomers", cleanupResult.getTotalDeletedCustomers());
            result.put("deletedRepayPlans", cleanupResult.getTotalDeletedRepayPlans());
            
            log.info("数据清理完成，结果: {}", cleanupResult.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "执行数据清理失败: " + e.getMessage());
            log.error("执行数据清理失败", e);
        }
        return result;
    }
    
    /**
     * 按月份删除指定数量的订单及相关数据
     * @param month 月份（格式：yyyy-MM）
     * @param deleteCount 删除数量
     */
    @PostMapping("/delete-by-month")
    public Map<String, Object> deleteOrdersByMonth(
            @RequestParam("month") String month,
            @RequestParam("deleteCount") int deleteCount) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("开始删除月份 {} 的 {} 个订单", month, deleteCount);
            HaohanLoanDataCleanupService.DeleteResult deleteResult = 
                    haohanLoanDataCleanupService.deleteOrdersByMonth(month, deleteCount);
            
            result.put("success", deleteResult.isSuccess());
            result.put("message", deleteResult.getMessage());
            result.put("deletedOrders", deleteResult.getDeletedOrders());
            result.put("deletedCustomers", deleteResult.getDeletedCustomers());
            result.put("deletedRepayPlans", deleteResult.getDeletedRepayPlans());
            result.put("deletedAmount", deleteResult.getDeletedAmount());
            
            log.info("删除月份 {} 数据完成，结果: {}", month, deleteResult.getMessage());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除月份数据失败: " + e.getMessage());
            log.error("删除月份 {} 数据失败", month, e);
        }
        return result;
    }
    
    /**
     * 获取清理预览信息
     */
    @GetMapping("/cleanup-preview")
    public Map<String, Object> getCleanupPreview(@RequestParam(value = "targetAmount", required = false) String targetAmount) {
        Map<String, Object> result = new HashMap<>();
        try {
            BigDecimal target = new BigDecimal("600000000"); // 默认六亿
            if (targetAmount != null && !targetAmount.trim().isEmpty()) {
                target = new BigDecimal(targetAmount);
            }
            
            // 获取当前总金额
            BigDecimal currentTotalAmount = haohanLoanDataCleanupService.getTotalRemainAmount();
            
            // 获取月度统计
            List<HaohanLoanDataCleanupService.MonthlyOrderStats> monthlyStats = 
                    haohanLoanDataCleanupService.getMonthlyOrderStats();
            
            // 计算需要删除的金额
            BigDecimal amountToDelete = currentTotalAmount.subtract(target);
            
            result.put("success", true);
            result.put("currentTotalAmount", currentTotalAmount);
            result.put("targetAmount", target);
            result.put("amountToDelete", amountToDelete);
            result.put("monthlyStats", monthlyStats);
            result.put("needCleanup", amountToDelete.compareTo(BigDecimal.ZERO) > 0);
            result.put("message", "获取清理预览信息成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取清理预览信息失败: " + e.getMessage());
            log.error("获取清理预览信息失败", e);
        }
        return result;
    }
}




